//
//  KYTabBar.swift
//  NormalHE
//
//  Created by SHANGLU on 16/12/29.
//  Copyright © 2016年 heky. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
class KYTabBar: UIView {

    lazy var tabBarButtons:[KYTabBarButton] = {
        return []
    }()
    let disposeBag:DisposeBag = DisposeBag()
    private(set) weak var selectedBtn:UIButton?
    private(set) weak var plusBtn:UIButton!
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        let plusButton = UIButton(type: .Custom)
        plusButton.setImage(UIImage(named: "selected_mine"), forState: .Normal)
        plusButton.setImage(UIImage(named: "selected_mine"), forState: .Selected)
        plusButton.sizeToFit()
        plusButton.rx_tap.subscribeNext { [weak self](sender) in
            
            
        }.addDisposableTo(self.disposeBag)

        self.addSubview(plusButton)
        self.plusBtn = plusButton
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func addTabBarButton(item:UITabBarItem){
    
        let btn = KYTabBarButton()
        self.addSubview(btn)
        btn.item = item
        self.tabBarButtons.append(btn)
        btn.addTarget(self, action: #selector(KYTabBar.onClick(_:)), forControlEvents: .TouchDown)
   
        //默认选中按钮
        if self.tabBarButtons.count == 1{
            self.onClick(btn)
        }
    }
    
    func onClick(sender:KYTabBarButton){
        self.selectedBtn?.selected = false
        sender.selected = true
        self.selectedBtn = sender

    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let W = self.frame.size.width
        let H = self.frame.size.height
        self.plusBtn.center = CGPoint(x: W * 0.5, y: H * 0.5)
        var btnX:CGFloat = 0
        let btnY:CGFloat = 0
        let btnW = W / CGFloat(self.subviews.count)
        let btnH = H
        self.tabBarButtons.toObservable().subscribeNext { (btn) in
            let index = self.tabBarButtons.indexOf(btn)!
            btnX = CGFloat(index) * btnW
            if index > 1{
                btnX += btnW
            }
            btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            btn.tag = index
        }.addDisposableTo(self.disposeBag)
        
    }
}
